package com.qf.controller;

import com.qf.util.CaptchaUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;

/**
 * 验证码控制器
 *
 * @USER: Administrator
 * @DATE: 2025/8/31 上午9:09
 * @VERSION: 1.0.0
 */
@Controller
public class CaptchaController {
    /**
     * 生成验证码图片
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 设置响应类型为图片
        response.setContentType("image/jpeg");

        // 生成验证码并写入响应流
        OutputStream os = response.getOutputStream();
        String captcha = CaptchaUtils.generateCaptcha(os);

        // 将验证码存入Session，用于后续验证
        HttpSession session = request.getSession();
        session.setAttribute("SESSION_CAPTCHA", captcha);

        os.flush();
        os.close();
    }
}
